/**
 * The Attribute object is the representation of a Monument (entity) properties.
 * It consists of two strings:
 *    - name: is used to store the name of the property
 *    - content: is used to store the value of the property
 * Although two attributes happen to have the same name and content,
 * an attribute can only belong to an Item.
 */ 

package models;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToOne;

import play.db.jpa.Model;

@Entity
public class Attribute extends Model{
	
	String name;
	
	@Lob
	public String content;
	
	/**
	 * Enabled specifies if this Attribute will be included
	 * in the user preferences to search the final Item
	 */
	public Boolean enabled;
	
	@ManyToOne
    public Item item;
	
	/**
	 * Empty Attribute constructor
	 */
	public Attribute(){
		name="";
		content="";
		enabled=false;
	}
	
	/** 
	 * Attribute constructor
	 * @param item item to which the attribute belongs
	 * @param name the name of the property
	 * @param content the value of the property
	 */
	public Attribute (Item item, String name, String content){
		this.item = item;
		this.name = name;
		this.content = content;
		this.enabled = false;
	}
	
	/** 
	 * Attribute constructor
	 * @param item item to which the attribute belongs
	 * @param name the name of the property
	 * @param content the value of the property
	 * @param enabled says if an attribute is enabled for using it when looking
	 * for similar objects
	 */
	public Attribute (Item item, String name, String content, Boolean enabled){
		this.item = item;
		this.name = name;
		this.content = content;
		this.enabled = enabled;
	}
	
	/**
	 * If enabled is true, then this attribute will be used as preference for the final search
	 */
	public void switchEnabled(){
		if (this.enabled==true) this.enabled=false;
		else this.enabled=true;
	}
	
	/**
	 * Used for Categories only. Leaves only the 1st part of the URI and replaces underscores with spaces. Also decodes the URI string, for example converts umlauts.
	 */
	public String toString() {
		String[] names = content.split(":");
		try {
			return URLDecoder.decode(names[names.length - 1].replace("_", " "), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			return names[names.length - 1].replace("_", " ");
		}
	}

}
